#!/bin/sh

printUsage()
{
	echo "updateDb.sh [-oudpfh]"
	echo "o: adresse du serveur (localhost)"
	echo "u: utilisateur (root)"
	echo "d: nom de la base de données (coMexpert)"
	echo "p: mot de passe de l'utilisateur"
	echo "f: fichier dump de la base de données généré par makeSchema (/usr/share/coMexpert/coMexpert.tar.gz)"
	echo "s: commande syncDb (/usr/share/coMexpert/syncDb)"
	echo "h: affiche l'aide et quitte"
}

hval="localhost"
uval="root"
dval="coMexpert"
mdpVal=""
mpdMySQL=""
mdpSyncDb=""
dumpFileName="/usr/share/coMexpert/coMexpert.tar.gz"
syncDbCmd="/usr/share/coMexpert/syncDb"

while getopts o:u:d:f:p:s:h name
do
	case $name in
		o)
			hval="$OPTARG"
			;;
		u)
			uval="$OPTARG"
			;;
		d)
			dval="$OPTARG"
			;;
		p)
			mdpMySQL="--password=$OPTARG"
			mdpSyncDb="-ps $OPTARG"
			;;
		f)
			dumpFileName="$OPTARG"
			;;
		s)
			syncDbCmd="$OPTARG"
			;;
		h)
			printUsage
			exit 0
			;;
		*)
			printUsage
			exit 0
			;;
	esac
done

tmpDbName="`date "+%Y%m%d"`_tmp_coMexpert"

tar -xzf $dumpFileName

mysqladmin -h $hval -u $uval $mdpMySQL create $tmpDbName
mysql -h $hval -u $uval $mdpMySQL $tmpDbName < coMexpert.sql
echo "Synchro de la base"
$syncDbCmd -hs $hval -us $uval $mdpSyncDb -dbs $tmpDbName -dbd $dval -c

echo "Création du schéma"
mysql -h $hval -u $uval $mdpMySQL $dval --execute "delete from $dval.schema"
mysql -h $hval -u $uval $mdpMySQL $dval  < schema.sql

echo "Création de la table des recherches liées"
mysql -h $hval -u $uval $mdpMySQL $dval --execute "delete from $dval.rechercheLier"
mysql -h $hval -u $uval $mdpMySQL $dval  < rechercheLier.sql

echo "Affectation de la version minimum du logiciel"
mysql -h $hval -u $uval $mdpMySQL $dval --execute "delete from $dval.version"
mysql -h $hval -u $uval $mdpMySQL $dval < version.sql

echo "Supression des triggers"
TRIGGERS=`mysql -h $hval -u $uval $mdpMySQL $dval --skip-column-names --execute "show triggers" | awk '{print $1}'`
for TRIGGER in $TRIGGERS
do
	mysql -h $hval -u $uval $mdpMySQL $dval --execute "DROP TRIGGER $dval.$TRIGGER"
done
echo "Création des triggers"
mysql -h $hval -u $uval $mdpMySQL $dval < triggers.sql

echo "Supression des procédures"
FUNCTIONS=`mysql -h $hval -u $uval $mdpMySQL $dval --skip-column-names --execute "show function status" | awk '{print $2}'`
for FUNCTION in $FUNCTIONS
do
	mysql -h $hval -u $uval $mdpMySQL $dval --execute "DROP FUNCTION IF EXISTS $dval.$FUNCTION"
done
echo "Création des procédures"
mysql -h $hval -u $uval $mdpMySQL $dval < procedure.sql

mysqladmin -h $hval -u $uval $mdpMySQL -f drop $tmpDbName
